/**
 * LLM智能对话助手 JavaScript
 */

class LLMChatApp {
    constructor() {
        this.ws = null;
        this.isConnected = false;
        this.sessionId = 'default';
        this.messageCount = 0;
        this.currentMessage = '';
        this.imageData = null;  // 存储上传的图像数据
        this.isStreamingResponse = false;  // 标记是否正在接收流式响应
        this.toolCallsContainer = null;  // 当前工具调用容器
        this.llmResponseContainer = null;  // LLM回复容器
        this.toolResults = new Map();  // 存储工具调用结果
        this.init();
    }

    init() {
        // 绑定事件
        this.bindEvents();
        
        // 连接WebSocket
        this.connectWebSocket();
        
        // 加载系统信息
        this.loadSystemInfo();
        
        // 加载可用工具
        this.loadAvailableTools();
        
        // 初始化状态
        this.updateConnectionStatus('connecting', '连接中...');
        
        // 初始化发送按钮状态
        this.updateSendButtonState();
    }

    bindEvents() {
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        
        // 发送按钮点击事件
        sendButton.addEventListener('click', () => this.sendMessage());
        
        // 输入框事件
        messageInput.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'Enter') {
                e.preventDefault();
                this.sendMessage();
            }
        });
        
        messageInput.addEventListener('input', () => {
            this.updateCharCount();
            this.autoResize();
        });
        
        // 初始化字符计数
        this.updateCharCount();
    }

    connectWebSocket() {
        try {
            this.ws = new WebSocket(`ws://${window.location.host}/ws`);
            
            this.ws.onopen = () => {
                this.isConnected = true;
                this.updateConnectionStatus('connected', '已连接');
                this.showNotification('WebSocket连接成功', 'success');
            };
            
            this.ws.onmessage = (event) => {
                this.handleWebSocketMessage(event);
            };
            
            this.ws.onclose = () => {
                this.isConnected = false;
                this.updateConnectionStatus('disconnected', '连接断开');
                this.showNotification('WebSocket连接断开', 'warning');
                
                // 尝试重连
                setTimeout(() => {
                    if (!this.isConnected) {
                        this.connectWebSocket();
                    }
                }, 3000);
            };
            
            this.ws.onerror = (error) => {
                this.updateConnectionStatus('error', '连接错误');
                this.showNotification('WebSocket连接错误', 'error');
                console.error('WebSocket error:', error);
            };
            
        } catch (error) {
            this.updateConnectionStatus('error', '连接失败');
            this.showNotification('无法建立WebSocket连接', 'error');
            console.error('WebSocket connection failed:', error);
        }
    }

    handleWebSocketMessage(event) {
        try {
            const data = JSON.parse(event.data);

            switch (data.type) {
                case 'content':
                    this.appendToCurrentMessage(data.content);
                    break;

                case 'tool_calling':
                    this.initToolCallingContainer();
                    break;

                case 'tool_start':
                    this.addToolStart(data.tool_name, data.tool_id);
                    break;

                case 'tool_result':
                    this.addToolResult(data.tool_name, data.tool_id, data.result, data.error);
                    break;

                case 'complete':
                    this.completeMessage();
                    break;

                case 'error':
                    this.showError(data.error, data.hint);
                    break;

                default:
                    console.log('Unknown message type:', data.type);
            }
        } catch (error) {
            console.error('Error parsing WebSocket message:', error);
        }
    }

    sendMessage() {
        const messageInput = document.getElementById('messageInput');
        const message = messageInput.value.trim();
        
        // 如果正在流式响应中，阻止发送新消息
        if (this.isStreamingResponse) {
            this.showNotification('请等待当前回复完成', 'warning');
            return;
        }
        
        if ((!message && !this.hasImage()) || !this.isConnected) {
            return;
        }
        
        // 显示用户消息（包括图像）
        if (this.hasImage()) {
            this.addUserMessageWithImage(message, this.imageData);
        } else {
            this.addMessage('user', message);
        }
        
        // 清空输入框
        messageInput.value = '';
        this.updateCharCount();
        this.autoResize();
        
        // 准备接收助手回复
        this.prepareAssistantMessage();
        
        // 构建发送数据
        const sendData = {
            message: message,
            session_id: this.sessionId
        };
        
        // 如果有图像数据，添加到发送数据中
        if (this.hasImage()) {
            sendData.image_data = this.imageData;
            // 发送后清除图像
            this.removeImage();
        }
        
        // 发送到WebSocket
        this.ws.send(JSON.stringify(sendData));
        
        // 更新消息计数
        this.messageCount += 2; // 用户消息 + 助手回复
        this.updateHistoryCount();
    }

    sendDemoMessage(message) {
        const messageInput = document.getElementById('messageInput');
        messageInput.value = message;
        this.updateCharCount();
        this.sendMessage();
    }

    async sendImageDemoMessage(imagePath, message) {
        try {
            // 获取图像数据
            const response = await fetch(imagePath);
            const blob = await response.blob();
            
            // 转换为base64
            const reader = new FileReader();
            reader.onload = (e) => {
                this.imageData = e.target.result;
                this.showImagePreview(this.imageData);
                
                // 设置消息文本
                const messageInput = document.getElementById('messageInput');
                messageInput.value = message;
                this.updateCharCount();
                
                // 发送消息
                this.sendMessage();
            };
            reader.readAsDataURL(blob);
        } catch (error) {
            console.error('Failed to load demo image:', error);
            this.showNotification('无法加载演示图像', 'error');
        }
    }

    addMessage(role, content, isStreaming = false) {
        const messagesContainer = document.getElementById('messagesContainer');
        
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${role}-message`;
        
        const avatar = document.createElement('div');
        avatar.className = 'message-avatar';
        avatar.textContent = role === 'user' ? '👤' : '🤖';
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        
        if (isStreaming) {
            contentDiv.innerHTML = '<span class="typing-indicator">正在输入...</span>';
            messageDiv.id = 'current-assistant-message';
        } else {
            contentDiv.innerHTML = this.formatMessage(content);
        }
        
        messageDiv.appendChild(avatar);
        messageDiv.appendChild(contentDiv);
        
        messagesContainer.appendChild(messageDiv);
        this.scrollToBottom();
        
        return messageDiv;
    }

    prepareAssistantMessage() {
        this.currentMessage = '';
        this.isStreamingResponse = true;  // 标记开始流式响应
        this.updateSendButtonState();     // 更新发送按钮状态
        this.addMessage('assistant', '', true);
    }

    appendToCurrentMessage(content) {
        this.currentMessage += content;
        const currentMessageElement = document.getElementById('current-assistant-message');
        if (currentMessageElement) {
            const contentDiv = currentMessageElement.querySelector('.message-content');
            contentDiv.innerHTML = this.formatMessage(this.currentMessage);
            this.scrollToBottom();
        }
    }

    completeMessage() {
        const currentMessageElement = document.getElementById('current-assistant-message');
        if (currentMessageElement) {
            currentMessageElement.removeAttribute('id');
        }
        this.currentMessage = '';
        this.isStreamingResponse = false;  // 标记流式响应结束
        this.updateSendButtonState();      // 更新发送按钮状态
    }

    initToolCallingContainer() {
        const currentMessageElement = document.getElementById('current-assistant-message');
        if (currentMessageElement) {
            const contentDiv = currentMessageElement.querySelector('.message-content');

            // 创建LLM回复内容区域
            this.llmResponseContainer = document.createElement('div');
            this.llmResponseContainer.className = 'llm-response-content';
            this.llmResponseContainer.style.display = 'none';

            // 创建工具调用容器
            this.toolCallsContainer = document.createElement('div');
            this.toolCallsContainer.className = 'tool-calling-container';
            this.toolCallsContainer.innerHTML = `
                <div class="tool-calling-header">
                    <span class="tool-calling-icon">🔧</span>
                    <span>正在调用工具...</span>
                </div>
                <div class="tool-results"></div>
            `;

            // 清空内容并添加组件：LLM回复在上，工具调用在下
            contentDiv.innerHTML = '';
            contentDiv.appendChild(this.llmResponseContainer);
            contentDiv.appendChild(this.toolCallsContainer);

            this.toolResults.clear();
            this.scrollToBottom();
        }
    }

    addToolStart(toolName, toolId) {
        if (!this.toolCallsContainer) return;

        const toolResultsDiv = this.toolCallsContainer.querySelector('.tool-results');

        // 创建工具结果项
        const toolResultItem = document.createElement('div');
        toolResultItem.className = 'tool-result-item';
        toolResultItem.id = `tool-${toolId}`;
        toolResultItem.innerHTML = `
            <div class="tool-result-header">
                <span class="tool-result-name">${toolName}</span>
                <span class="tool-result-status running">运行中</span>
            </div>
            <div class="tool-result-content">正在执行...</div>
        `;

        toolResultsDiv.appendChild(toolResultItem);
        this.scrollToBottom();
    }

    addToolResult(toolName, toolId, result, isError = false) {
        const toolResultItem = document.getElementById(`tool-${toolId}`);
        if (!toolResultItem) return;

        const statusSpan = toolResultItem.querySelector('.tool-result-status');
        const contentDiv = toolResultItem.querySelector('.tool-result-content');

        // 更新状态
        statusSpan.className = `tool-result-status ${isError ? 'error' : 'completed'}`;
        statusSpan.textContent = isError ? '错误' : '完成';

        // 更新内容，限制长度
        let displayResult = result;
        if (displayResult.length > 500) {
            displayResult = displayResult.substring(0, 500) + '...\n[结果过长，已截断]';
        }

        contentDiv.textContent = displayResult;
        if (isError) {
            contentDiv.classList.add('error');
            toolResultItem.classList.add('error');
        }

        this.scrollToBottom();
    }

    appendToCurrentMessage(content) {
        this.currentMessage += content;

        // 如果有LLM回复容器，更新LLM回复部分
        if (this.llmResponseContainer) {
            if (this.currentMessage.trim()) {
                this.llmResponseContainer.style.display = 'block';
                this.llmResponseContainer.innerHTML = this.formatMessage(this.currentMessage);
            }
        } else {
            // 没有工具调用的常规处理
            const currentMessageElement = document.getElementById('current-assistant-message');
            if (currentMessageElement) {
                const contentDiv = currentMessageElement.querySelector('.message-content');
                contentDiv.innerHTML = this.formatMessage(this.currentMessage);
            }
        }

        this.scrollToBottom();
    }

    completeMessage() {
        const currentMessageElement = document.getElementById('current-assistant-message');
        if (currentMessageElement) {
            currentMessageElement.removeAttribute('id');
        }

        this.currentMessage = '';
        this.toolCallsContainer = null;
        this.llmResponseContainer = null;
        this.toolResults.clear();
        this.isStreamingResponse = false;
        this.updateSendButtonState();
    }
    
    showError(error, hint) {
        const currentMessageElement = document.getElementById('current-assistant-message');
        if (currentMessageElement) {
            const contentDiv = currentMessageElement.querySelector('.message-content');
            contentDiv.innerHTML = `<div class="error-message">❌ 错误: ${error.message}<br>💡 ${hint}</div>`;
            currentMessageElement.removeAttribute('id');
        }
        this.isStreamingResponse = false;  // 标记响应结束
        this.updateSendButtonState();      // 更新发送按钮状态
        this.scrollToBottom();
    }

    // 添加用户消息（包含图像）
    addUserMessageWithImage(message, imageData) {
        const messagesContainer = document.getElementById('messagesContainer');
        
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message user-message';
        
        const avatar = document.createElement('div');
        avatar.className = 'message-avatar';
        avatar.textContent = '👤';
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        
        // 如果有文本消息，先显示文本
        if (message) {
            const textDiv = document.createElement('div');
            textDiv.innerHTML = this.formatMessage(message);
            contentDiv.appendChild(textDiv);
        }
        
        // 添加图像预览
        const imagePreviewDiv = document.createElement('div');
        imagePreviewDiv.className = 'image-preview-container';
        imagePreviewDiv.innerHTML = `<img src="${imageData}" alt="上传的图像" class="uploaded-image-preview">`;
        contentDiv.appendChild(imagePreviewDiv);
        
        messageDiv.appendChild(avatar);
        messageDiv.appendChild(contentDiv);
        
        messagesContainer.appendChild(messageDiv);
        this.scrollToBottom();
    }

    formatMessage(content) {
        // 简单的Markdown格式化
        return content
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/\*(.*?)\*/g, '<em>$1</em>')
            .replace(/`(.*?)`/g, '<code>$1</code>')
            .replace(/\n/g, '<br>');
    }

    scrollToBottom() {
        const messagesContainer = document.getElementById('messagesContainer');
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    updateCharCount() {
        const messageInput = document.getElementById('messageInput');
        const charCount = document.getElementById('charCount');
        const length = messageInput.value.length;
        charCount.textContent = `${length}/2000`;
        
        if (length > 1800) {
            charCount.style.color = '#e74c3c';
        } else if (length > 1500) {
            charCount.style.color = '#f39c12';
        } else {
            charCount.style.color = '#7f8c8d';
        }
    }

    autoResize() {
        const messageInput = document.getElementById('messageInput');
        messageInput.style.height = 'auto';
        messageInput.style.height = Math.min(messageInput.scrollHeight, 120) + 'px';
    }

    updateConnectionStatus(status, text) {
        const statusDot = document.getElementById('statusDot');
        const statusText = document.getElementById('statusText');
        
        statusDot.className = 'status-dot';
        if (status === 'connected') {
            statusDot.classList.add('connected');
        } else if (status === 'error') {
            statusDot.classList.add('error');
        }
        
        statusText.textContent = text;
    }

    async loadSystemInfo() {
        try {
            const response = await fetch('/config');
            const config = await response.json();
            
            document.getElementById('modelName').textContent = config.model || '未知';
            document.getElementById('fcStatus').textContent = config.function_calling_enabled ? '✅ 已启用' : '❌ 已禁用';
            document.getElementById('mcpStatus').textContent = config.mcp_enabled ? '✅ 已启用' : '❌ 已禁用';
            
            // 添加VLM状态显示（如果配置中包含VLM信息）
            if (config.vlm_enabled !== undefined) {
                const vlmStatus = document.createElement('div');
                vlmStatus.className = 'info-item';
                vlmStatus.innerHTML = `
                    <span class="info-label">VLM视觉模型:</span>
                    <span class="info-value">${config.vlm_enabled ? '✅ 已启用' : '❌ 已禁用'}</span>
                `;
                document.querySelector('.system-info').appendChild(vlmStatus);
            }
            
        } catch (error) {
            console.error('Failed to load system info:', error);
        }
    }

    async loadAvailableTools() {
        try {
            // 并行获取工具信息和MCP配置
            const [toolsResponse, mcpConfigResponse] = await Promise.all([
                fetch('/tools'),
                fetch('/mcp-config')
            ]);

            const tools = await toolsResponse.json();
            const mcpConfig = await mcpConfigResponse.json();

            const toolsList = document.getElementById('toolsList');
            toolsList.innerHTML = '';

            // Function Calling工具分类
            const fcCategories = {
                'system': { name: '系统管理', icon: '⚙️', tools: [] },
                'multimedia': { name: '多媒体控制', icon: '🎵', tools: [] },
                'gimbal': { name: '云台控制', icon: '📹', tools: [] },
                'robotic_arm': { name: '机械臂控制', icon: '🦾', tools: [] },
                'file': { name: '文件操作', icon: '📁', tools: [] },
                'network': { name: '网络通信', icon: '🌐', tools: [] },
                'math': { name: '数学计算', icon: '🧮', tools: [] },
                'vision': { name: '物体检测', icon: '👁️', tools: [] },
                'other': { name: '其他工具', icon: '🔧', tools: [] }
            };

            // MCP服务器分组
            const mcpServers = {};

            // 分类函数
            function categorizeTool(toolName, description) {
                const name = toolName.toLowerCase();
                const desc = description.toLowerCase();

                // VLM视觉相关工具优先级最高
                if (name.includes('vlm_') || name.includes('read_text') || name.includes('analyze_image') ||
                    name.includes('detect_objects') || name.includes('visual_question') ||
                    name.includes('vision') || desc.includes('图像分析') || desc.includes('文字识别') ||
                    desc.includes('物体检测') || desc.includes('视觉') || desc.includes('边界框')) {
                    return 'vision';
                }

                // 云台控制工具
                if (name.includes('gimbal_') || name.includes('gimbal') || desc.includes('云台')) {
                    return 'gimbal';
                }

                // 机械臂控制工具
                if (name.includes('arm_') || name.includes('catch_object') || name.includes('put_object') ||
                    name.includes('stack_put_object') || desc.includes('机械臂') ||
                    desc.includes('夹爪') || desc.includes('抓取') || desc.includes('放置') ||
                    desc.includes('堆叠')) {
                    return 'robotic_arm';
                }

                if (name.includes('volume') || name.includes('music') || name.includes('play') ||
                    name.includes('audio') || name.includes('sound') || desc.includes('音频') ||
                    desc.includes('音乐') || desc.includes('播放') || desc.includes('音量')) {
                    return 'multimedia';
                }

                if (name.includes('file') || name.includes('read') || name.includes('write') ||
                    name.includes('list') || name.includes('delete') || desc.includes('文件') ||
                    desc.includes('目录') || desc.includes('读取') || desc.includes('写入')) {
                    return 'file';
                }

                if (name.includes('http') || name.includes('request') || name.includes('api') ||
                    name.includes('websocket') || name.includes('url') || desc.includes('网络') ||
                    desc.includes('请求') || desc.includes('连接')) {
                    return 'network';
                }

                if (name.includes('calculate') || name.includes('math') || name.includes('compute') ||
                    name.includes('sin') || name.includes('cos') || name.includes('sqrt') ||
                    desc.includes('计算') || desc.includes('数学') || desc.includes('三角')) {
                    return 'math';
                }

                if (name.includes('system') || name.includes('config') || name.includes('status') ||
                    name.includes('info') || desc.includes('系统') || desc.includes('配置') ||
                    desc.includes('状态') || desc.includes('信息')) {
                    return 'system';
                }

                return 'other';
            }

            // 获取MCP服务器显示名称（从配置文件中获取）
            function getServerDisplayName(serverName) {
                // 如果配置文件中有自定义名称，使用配置的名称
                if (mcpConfig.mcpServers && mcpConfig.mcpServers[serverName] && mcpConfig.mcpServers[serverName].displayName) {
                    return mcpConfig.mcpServers[serverName].displayName;
                }

                // 否则直接使用服务器名称，添加图标前缀
                return `📦 ${serverName}`;
            }

            // 处理Function Calling工具 (本地工具，不显示MCP标签)
            if (tools.function_calling && tools.function_calling.length > 0) {
                tools.function_calling.forEach(tool => {
                    const category = categorizeTool(tool.function.name, tool.function.description);
                    fcCategories[category].tools.push({
                        name: tool.function.name,
                        description: tool.function.description,
                        type: 'function_calling'
                    });
                });
            }

            // 处理MCP工具 (按服务器分组)
            if (tools.mcp_tools && tools.mcp_tools.length > 0) {
                tools.mcp_tools.forEach(tool => {
                    const serverName = tool.server_name || 'unknown';
                    if (!mcpServers[serverName]) {
                        mcpServers[serverName] = {
                            displayName: getServerDisplayName(serverName),
                            tools: []
                        };
                    }
                    mcpServers[serverName].tools.push({
                        name: tool.function.name,
                        description: tool.function.description,
                        type: 'mcp',
                        serverName: serverName
                    });
                });
            }

            let hasTools = false;

            // 渲染Function Calling工具 (按功能分类)
            Object.keys(fcCategories).forEach(categoryKey => {
                const category = fcCategories[categoryKey];
                if (category.tools.length > 0) {
                    hasTools = true;

                    const categoryDiv = document.createElement('div');
                    categoryDiv.className = 'tool-category';
                    categoryDiv.innerHTML = `
                        <div class="category-header clickable" onclick="toggleToolCategory(this)">
                            <span class="category-icon">${category.icon}</span>
                            <span class="category-name">${category.name}</span>
                            <span class="category-count">${category.tools.length}个工具</span>
                            <span class="category-toggle">▼</span>
                        </div>
                        <div class="category-tools expanded"></div>
                    `;

                    const categoryTools = categoryDiv.querySelector('.category-tools');

                    category.tools.forEach(tool => {
                        const toolDiv = document.createElement('div');
                        toolDiv.className = 'tool-item';
                        toolDiv.innerHTML = `
                            <div class="tool-name">${tool.name}</div>
                            <div class="tool-desc">${tool.description}</div>
                        `;
                        categoryTools.appendChild(toolDiv);
                    });

                    toolsList.appendChild(categoryDiv);
                }
            });

            // 渲染MCP工具 (按服务器分组)
            Object.keys(mcpServers).forEach(serverName => {
                const server = mcpServers[serverName];
                if (server.tools.length > 0) {
                    hasTools = true;

                    const serverDiv = document.createElement('div');
                    serverDiv.className = 'mcp-server-category';
                    serverDiv.innerHTML = `
                        <div class="category-header clickable mcp-header" onclick="toggleToolCategory(this)">
                            <span class="category-icon">📡</span>
                            <span class="category-name">${server.displayName}</span>
                            <span class="category-count">${server.tools.length}个工具</span>
                            <span class="mcp-badge">MCP</span>
                            <span class="category-toggle">▼</span>
                        </div>
                        <div class="category-tools expanded"></div>
                    `;

                    const categoryTools = serverDiv.querySelector('.category-tools');

                    server.tools.forEach(tool => {
                        const toolDiv = document.createElement('div');
                        toolDiv.className = 'tool-item mcp-tool';
                        toolDiv.innerHTML = `
                            <div class="tool-name">${tool.name}</div>
                            <div class="tool-desc">${tool.description}</div>
                        `;
                        categoryTools.appendChild(toolDiv);
                    });

                    toolsList.appendChild(serverDiv);
                }
            });

            if (!hasTools) {
                toolsList.innerHTML = '<div class="loading">暂无可用工具</div>';
            }

        } catch (error) {
            console.error('Failed to load tools:', error);
            document.getElementById('toolsList').innerHTML = '<div class="loading">加载失败</div>';
        }
    }

    updateHistoryCount() {
        document.getElementById('historyCount').textContent = `${this.messageCount}条`;
    }

    async clearConversation() {
        if (!confirm('确定要清空当前对话吗？')) {
            return;
        }
        
        try {
            const response = await fetch(`/conversations/${this.sessionId}`, {
                method: 'DELETE'
            });
            
            if (response.ok) {
                // 清空所有消息
                const messagesContainer = document.getElementById('messagesContainer');
                messagesContainer.innerHTML = '';
                
                this.messageCount = 0;
                this.updateHistoryCount();
                this.showNotification('对话已清空', 'success');
            } else {
                this.showNotification('清空对话失败', 'error');
            }
        } catch (error) {
            console.error('Failed to clear conversation:', error);
            this.showNotification('清空对话失败', 'error');
        }
    }

    showNotification(message, type = 'info') {
        const notification = document.getElementById('notification');
        const notificationText = document.getElementById('notificationText');
        
        notificationText.textContent = message;
        notification.className = `notification ${type}`;
        notification.style.display = 'flex';
        
        // 3秒后自动隐藏
        setTimeout(() => {
            this.hideNotification();
        }, 3000);
    }

    hideNotification() {
        const notification = document.getElementById('notification');
        notification.style.display = 'none';
    }

    // 图像上传处理
    handleImageUpload(event) {
        const file = event.target.files[0];
        if (!file) return;

        // 检查文件类型
        if (!file.type.startsWith('image/')) {
            this.showNotification('请选择图像文件', 'error');
            return;
        }

        // 检查文件大小 (最大10MB)
        if (file.size > 10 * 1024 * 1024) {
            this.showNotification('图像文件过大，请选择小于10MB的文件', 'error');
            return;
        }

        const reader = new FileReader();
        reader.onload = (e) => {
            this.imageData = e.target.result;
            this.showImagePreview(this.imageData);
            this.showNotification('图像上传成功', 'success');
        };
        reader.readAsDataURL(file);
    }

    // 显示图像预览
    showImagePreview(imageData) {
        const imagePreview = document.getElementById('imagePreview');
        const removeButton = document.getElementById('removeImageButton');
        
        imagePreview.innerHTML = `<img src="${imageData}" alt="预览图像">`;
        imagePreview.style.display = 'block';
        removeButton.style.display = 'block';
    }

    // 移除图像
    removeImage() {
        this.imageData = null;
        document.getElementById('imageInput').value = '';
        document.getElementById('imagePreview').style.display = 'none';
        document.getElementById('removeImageButton').style.display = 'none';
    }

    // 检查是否有上传的图像
    hasImage() {
        return this.imageData !== null;
    }
    
    // 更新发送按钮状态
    updateSendButtonState() {
        const sendButton = document.getElementById('sendButton');
        const messageInput = document.getElementById('messageInput');
        
        if (this.isStreamingResponse) {
            sendButton.disabled = true;
            sendButton.textContent = '回复中...';
            sendButton.style.opacity = '0.6';
            messageInput.disabled = true;
        } else {
            sendButton.disabled = false;
            sendButton.textContent = '发送';
            sendButton.style.opacity = '1';
            messageInput.disabled = false;
        }
    }
}

// 全局函数
let app;

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    app = new LLMChatApp();
});

// 全局函数供HTML调用
function sendMessage() {
    app.sendMessage();
}

function sendDemoMessage(message) {
    app.sendDemoMessage(message);
}

function sendImageDemoMessage(imagePath, message) {
    app.sendImageDemoMessage(imagePath, message);
}

function clearConversation() {
    app.clearConversation();
}

function hideNotification() {
    app.hideNotification();
}

// 图像处理函数
function handleImageUpload(event) {
    app.handleImageUpload(event);
}

function removeImage() {
    app.removeImage();
}

// 子菜单切换函数
function toggleSubmenu(menuId, event) {
    const submenu = document.getElementById(menuId + '-submenu');
    const toggle = event.currentTarget;

    // 切换当前子菜单
    if (submenu.classList.contains('active')) {
        submenu.classList.remove('active');
        toggle.classList.remove('active');
    } else {
        submenu.classList.add('active');
        toggle.classList.add('active');
    }

    // 关闭其他子菜单（可选）
    const allSubmenus = document.querySelectorAll('.submenu-content');
    const allToggles = document.querySelectorAll('.submenu-toggle');

    allSubmenus.forEach(menu => {
        if (menu.id !== menuId + '-submenu') {
            menu.classList.remove('active');
        }
    });

    allToggles.forEach(btn => {
        if (btn !== toggle) {
            btn.classList.remove('active');
        }
    });
}

// 工具分类折叠功能
function toggleToolCategory(headerElement) {
    const categoryTools = headerElement.nextElementSibling;
    const toggle = headerElement.querySelector('.category-toggle');

    if (categoryTools.classList.contains('expanded')) {
        categoryTools.classList.remove('expanded');
        categoryTools.classList.add('collapsed');
        toggle.textContent = '▶';
    } else {
        categoryTools.classList.remove('collapsed');
        categoryTools.classList.add('expanded');
        toggle.textContent = '▼';
    }
}
